/*
 * @Author: gk 
 * @Date: 2018-04-14 12:36:45 
 * @Last Modified by: gk
 * @Last Modified time: 2018-04-24 14:22:54
 * 扩展layui select成为自动填充字段填充下拉框列表
 */

layui.define(['zlConfig', 'form'], function (exports) {
    "use strict";
    var $ = layui.$
        , zlConfig = layui.zlConfig
        , STATUSNAME = zlConfig.global.result.statusName
        , MSGNAME = zlConfig.global.result.msgName
        , DATANAME = zlConfig.global.result.dataName
        , ERROR = zlConfig.global.result.errorState
        , OK = zlConfig.global.result.okState
        , form = layui.form
        , obj = {};
    //组件重画消息处理
    layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.WM_DRAW, null, function (WParam) {
        if (WParam && $(WParam.elem).attr('class') && $(WParam.elem).attr('class').indexOf('select-ext') >= 0) {
            obj.render($(WParam.elem), WParam.value);
        }
    });
    obj = {
        render: function ($elem, value, reload) {
            var options = ($elem.attr('settings') ? eval('(' + $elem.attr('settings') + ')') : {})
                , dataurl = options.dataurl
                , datas = []
                , defaultOptions = {
                    method: 'get'
                    , titlefield: 'name'
                    , valuefield: 'value'
                    , params: '{}'
                    , dataurl: ""
                    , value: ""
                    , placeholder: "请选择"
                    , showtitleoption: true
                };
            if ($elem.is(':disabled')) {
                defaultOptions.placeholder = ' '
            }
            options = $.extend({}, defaultOptions, options);
            options.reload = reload;
            var isSuccess = false;
            if (!$elem.attr('loaded')||options.reload) {
                if ($elem.length != 1) {
                    layui.error("重复或不存在的组件名称[" + $elem.attr("name") + "]");
                    return;
                }
                $.ajax({
                    type: options.method
                    , async: false
                    , url: dataurl
                    , data: eval('(' + options.params + ')')
                    , dataType: 'json'
                    , success: function (res) {
                        if (res[STATUSNAME] == OK) {
                            datas = res[DATANAME];
                            isSuccess = true;
                            $elem.attr('loaded', 1);
                        } else {
                            throw Error(res[MSGNAME]);
                        }
                    }
                    , error: function (e, m) {
                        throw Error(m);
                    }
                });
            }
            else {
                isSuccess = true;
            }
            if (!isSuccess) { return; }
            options.value = ((value === undefined || value === null || value === "") ? options.value : value);
            if (options.value !== $elem.val()||options.reload) {
                obj.init($elem, options, datas);
            } else {
                $elem.val((options.value ? options.value : ''));
            }
        },
        init: function ($elem, options, datas) {
            var items = [],
                placeholder = $elem.attr('placeholder');
            placeholder = placeholder ? placeholder : options.placeholder;
            if(options.reload){
                $elem.empty();
            }
            
            if (datas.length > 0) {
                if (options.showtitleoption) {
                    items.push('<option value="">' + (placeholder ? placeholder : '请选择') + '</option>');
                }               
                for (var i = 0; i < datas.length; i++) {
                    items.push("<option value='" + datas[i][options.valuefield] + "' >" + datas[i][options.titlefield] + "</option>");
                }
                $elem.append(items.join(''));
            }
            var setValue = function (value) {
                $elem.val(value);
            };
            //初始化值
            setValue(options.value==='' ?'': options.value);
            // 如果是重新下载，需要自动渲染
            if(options.reload){
                // 根据filter渲染
                var filter = $elem.attr('lay-filter');
                if(filter){
                    form.render('select',filter);
                }else {
                    form.render('select');
                }
            }
        },
        reinit:function($elem,value){
            obj.render($elem,value,true);
        }
    }
    exports('zlSelectEx', obj);
});